#!/bin/env python
import time
import subprocess

from flask import Flask, render_template, request
from flask_socketio import SocketIO

from test.dns import nslookup, dig
# from test.websocket_tools import test
    
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)


@app.route('/')
def index():
    url = 'http://127.0.0.1:5000'
    return render_template('index.html', url=url)


@app.route('/shell_ping')
def shell_ping():
    addr = request.args.get('addr')
    cmd = "ping -c 5 " + addr
    p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
    while p.poll() is None: 
        socketio.emit('response3', str(p.stdout.readline()), namespace='/socket_ping')
    socketio.emit('response3', str(p.stdout.read()), namespace='/socket_ping')
    return addr


@app.route('/ping/')
def web_ping():
    return render_template('ping.html')


@app.route('/shell_nslookup', methods=['POST', 'GET'])
def shell_nslookup():
    domain = request.args.get('domain')
    res = nslookup(domain)
    return res


@app.route('/nslookup')
def web_nslookup():
    return render_template('nslookup.html')


@app.route('/shell_dig', methods=['POST', 'GET'])
def shell_dig():
    domain = request.args.get('domain')
    res = dig(domain)
    return res


@app.route('/dig')
def web_dig():
    return render_template('dig.html')


if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0',port=5000,debug=True)
